package com.gxuwz.weather;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.viewpager2.widget.ViewPager2;

import android.Manifest;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baidubce.http.ApiExplorerClient;
import com.baidubce.http.AppSigner;
import com.baidubce.http.HttpMethodName;
import com.baidubce.model.ApiExplorerRequest;
import com.baidubce.model.ApiExplorerResponse;
import com.gxuwz.weather.adapter.WeatherFragmentAdapter;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gxuwz.weather.db.CityDao;
import com.gxuwz.weather.db.CityDatabaseHelper;
import com.gxuwz.weather.dialog.UpdateDialog;
import com.gxuwz.weather.fragment.WeatherFragment;
import com.gxuwz.weather.model.VersionInfo;
import com.gxuwz.weather.utils.VersionUtils;
import com.gxuwz.weather.utils.UpdateChecker;
import com.gxuwz.weather.utils.ApkDownloader;
import com.airbnb.lottie.LottieAnimationView;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.lang.reflect.Type;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.location.Address;

import androidx.fragment.app.Fragment;
import android.util.Log;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.HttpUrl;

public class MainActivity extends AppCompatActivity {

    private static final String TOKEN = "c80b6e76998c5fe6bd03ada2ba6c22a2";

    private ViewPager2 viewPager;
    private WeatherFragmentAdapter weatherFragmentAdapter;
    private List<String> cityList;
    private LinearLayout llCityIndicators; // 城市指示器容器
    private List<ImageView> dotIndicators; //
    private LinearLayout bottomNavigationBar; // 添加底部导航栏引用
    private CityDao cityDao; // 添加CityDao引用

    private String gpsCity = null; // 存储定位到的城市名
    
    // 添加版本检查相关成员变量
    private UpdateChecker updateChecker;
    private ApkDownloader apkDownloader;
    private FrameLayout loadingLayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化数据库
        cityDao = new CityDao(this);
        cityDao.open();
        
        // 初始化版本检查工具
        updateChecker = new UpdateChecker(this);
        apkDownloader = new ApkDownloader(this);

        viewPager = findViewById(R.id.viewPager);
        llCityIndicators = findViewById(R.id.ll_city_indicators);
        bottomNavigationBar = findViewById(R.id.bottom_navigation_bar); // 初始化底部导航栏
        ImageView ivMenuIcon = findViewById(R.id.iv_menu_icon); // 右侧菜单图标
        loadingLayer = findViewById(R.id.loading_layer);

        // 启动时显示加载动画层
        loadingLayer.setVisibility(View.VISIBLE);

        // 从数据库加载城市列表
        cityList = new ArrayList<>();
        cityList.add(""); // 启动时用空字符串占位，防止内容区提前显示
        weatherFragmentAdapter = new WeatherFragmentAdapter(this, cityList);
        viewPager.setAdapter(weatherFragmentAdapter);

        // 初始化城市指示器
        setupCityIndicators(cityList.size());

        // 设置ViewPager页面切换监听器
        viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                updateCityIndicators(position);
            }
        });

        // 设置菜单图标点击事件
        ivMenuIcon.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, CityManageActivity.class);
            startActivity(intent);
        });

        // 设置版本检查监听器
        setupUpdateChecker();
        
        // 设置下载监听器
        setupApkDownloader();

//        CityDatabaseHelper dbHelper = new CityDatabaseHelper(this);
//            dbHelper.importAllCitiesFromAssets(this);

        requestLocationAndAddCity();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent); // 将新的intent设置为activity的当前intent
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cityDao != null) {
            cityDao.close();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 1. 重新加载城市列表
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        String gpsCity = prefs.getString("gps_city", null);
        List<String> dbCities = cityDao.getAllCities();

        cityList.clear();
        if (gpsCity != null && !gpsCity.isEmpty()) {
            cityList.add(gpsCity);
        }
        for (String c : dbCities) {
            if (!cityList.contains(c)) { // 防止重复添加
                cityList.add(c);
            }
        }

        // 2. 更新适配器
        if (weatherFragmentAdapter != null) {
            weatherFragmentAdapter.updateCityList(cityList);
        }

        // 3. 重新设置UI（指示器）
        setupCityIndicators(cityList.size());

        // 4. 处理从CityManageActivity返回的选中城市
        String selectedCity = getIntent().getStringExtra("selected_city");
        if (selectedCity != null && !selectedCity.isEmpty()) {
            int position = cityList.indexOf(selectedCity);
            if (position != -1) {
                viewPager.setCurrentItem(position, false);
            }
            // 清除intent中的数据，防止每次onResume都触发重复操作
            getIntent().removeExtra("selected_city");
        } else {
            // 如果没有指定城市，则恢复到之前的位置
            if (viewPager.getAdapter() != null && viewPager.getAdapter().getItemCount() > 0) {
                int currentPosition = Math.min(viewPager.getCurrentItem(), cityList.size() - 1);
                viewPager.setCurrentItem(currentPosition, false);
            }
        }
        
        // 5. 确保指示器状态正确
        updateCityIndicators(viewPager.getCurrentItem());
    }

//权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1001 && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            requestLocationAndAddCity();
        }
    }

    /**
     * 初始化城市指示器圆点
     * @param count 城市数量
     */
    private void setupCityIndicators(int count) {
        dotIndicators = new ArrayList<>();
        llCityIndicators.removeAllViews(); // 清除旧的视图

        // 确保count不超过实际城市数量
        count = Math.min(count, cityList.size());

        for (int i = 0; i < count; i++) {
            ImageView dot = new ImageView(this);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(4, 0, 4, 0);
            dot.setLayoutParams(params);
            dot.setImageResource(R.drawable.dot_indicator_inactive);
            dotIndicators.add(dot);
            llCityIndicators.addView(dot);
        }
    }

    /**
     * 更新城市指示器圆点状态
     * @param selectedPosition 当前选中的城市索引
     */
    private void updateCityIndicators(int selectedPosition) {
        for (int i = 0; i < dotIndicators.size(); i++) {
            if (i == selectedPosition) {
                dotIndicators.get(i).setImageResource(R.drawable.dot_indicator_active);
            } else {
                dotIndicators.get(i).setImageResource(R.drawable.dot_indicator_inactive);
            }
        }
    }

    // 点击更新时触发
    public void onUpdateClick(View view) {
        checkUpdate();
    }

    // 检查更新 - 使用真实的网络请求
    private void checkUpdate() {
        // 显示加载提示
        Toast.makeText(this, "正在检查更新...", Toast.LENGTH_SHORT).show();
        
        // 开始检查更新
        updateChecker.checkUpdate();
    }
    
    /**
     * 设置版本检查监听器
     */
    private void setupUpdateChecker() {
        updateChecker.setOnUpdateListener(new UpdateChecker.OnUpdateListener() {
            @Override
            public void onUpdateAvailable(VersionInfo versionInfo) {
                // 在主线程中显示更新对话框
                runOnUiThread(() -> {
                    showUpdateDialog(versionInfo);
                });
            }
            
            @Override
            public void onNoUpdate() {
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "已是最新版本", Toast.LENGTH_SHORT).show();
                });
            }
            
            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "检查更新失败: " + error, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    /**
     * 设置APK下载监听器
     */
    private void setupApkDownloader() {
        apkDownloader.setOnDownloadListener(new ApkDownloader.OnDownloadListener() {
            @Override
            public void onDownloadStart() {
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "开始下载新版本", Toast.LENGTH_SHORT).show();
                });
            }
            
            @Override
            public void onDownloadComplete(String filePath) {
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "下载完成，准备安装", Toast.LENGTH_SHORT).show();
                    // 自动安装APK
                    apkDownloader.installApk(filePath);
                });
            }
            
            @Override
            public void onDownloadFailed(String error) {
                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "下载失败: " + error, Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    // 显示更新对话框
    private void showUpdateDialog(VersionInfo versionInfo) {
        UpdateDialog dialog = new UpdateDialog(this, versionInfo, () -> {
            // 处理更新按钮点击事件
            startDownload(versionInfo);
        });
        dialog.show();
    }

    // 开始下载新版本
    private void startDownload(VersionInfo versionInfo) {
        // 生成文件名
        String fileName = "weather_" + versionInfo.getVersionName() + ".apk";
        // 开始下载到默认Download目录
        apkDownloader.startDownload(versionInfo.getDownloadUrl(), fileName);
        // 不再跳转到系统下载管理器，保持在App内
        // Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
        // startActivity(intent);
    }

    // 添加一个公共方法来更新底部导航栏颜色
    public void updateBottomNavigationBarColor(int color) {
        if (bottomNavigationBar != null) {
            bottomNavigationBar.setBackgroundColor(color);
        }
    }

    private void requestLocationAndAddCity() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1001);
            return;
        }
        locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, new LocationListener() {
            @Override
            public void onLocationChanged(@NonNull Location location) {
                double lat = location.getLatitude();
                double lng = location.getLongitude();
                new Thread(() -> {
                    try {
                        String path = "http://getweather.api.bdymkt.com/lundear/weather1d";
                        ApiExplorerRequest request = new ApiExplorerRequest(HttpMethodName.GET, path);
                        request.setCredentials("bd0695e091ee4f83a9e4739a5a6dd3d5", "c3e30f7501024ba1aa958007d6377769");
                        request.addHeaderParameter("Content-Type", "application/json; charset=utf-8");
                        request.addQueryParameter("lat", String.valueOf(lat));
                        request.addQueryParameter("lng", String.valueOf(lng));
                        ApiExplorerClient client = new ApiExplorerClient(new AppSigner());
                        ApiExplorerResponse response = client.sendRequest(request);
                        String json = response.getResult();
                        Log.d("定位城市", "接口原始返回: " + json);
                        JSONObject obj = new JSONObject(json);
                        JSONObject data = obj.optJSONObject("data");
                        final String cityName;
                        if (data != null) {
                            JSONObject cityInfo = data.optJSONObject("cityInfo");
                            if (cityInfo != null) {
                                cityName = cityInfo.optString("areaCn");
                            } else {
                                cityName = "";
                            }
                        } else {
                            cityName = "";
                        }
                        runOnUiThread(() -> {
                            gpsCity = cityName;
                            Log.d("定位城市", "接口返回城市名: " + gpsCity);
                            Toast.makeText(MainActivity.this, "定位到城市：" + gpsCity, Toast.LENGTH_LONG).show();
                            // 保存经纬度到SharedPreferences
                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                            prefs.edit().putString("gps_lat", String.valueOf(lat)).putString("gps_lng", String.valueOf(lng)).putString("gps_city", gpsCity).apply();
                            // 只在内存管理cityList，定位城市放第一个，后面是数据库城市
                            List<String> dbCities = cityDao.getAllCities();
                            cityList.clear();
                            cityList.add(gpsCity); // 定位城市
                            for (String c : dbCities) {
                                if (!c.equals(gpsCity)) {
                                    cityList.add(c);
                                }
                            }
                            Log.d("定位城市", "刷新后的cityList: " + cityList);
                            weatherFragmentAdapter.updateCityList(cityList);
                            viewPager.setAdapter(weatherFragmentAdapter);
                            // 关键：强制切换到第一个页面
                            viewPager.setCurrentItem(0, false);
                            Log.d("定位城市", "ViewPager当前页面: " + viewPager.getCurrentItem() + ", ARG_CITY: " + cityList.get(0));
                            // 定位和城市数据加载完成后，隐藏加载动画层
                            if (loadingLayer != null) loadingLayer.setVisibility(View.GONE);
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> {
                            Toast.makeText(MainActivity.this, "天气接口请求失败", Toast.LENGTH_SHORT).show();
                            // 即使失败也隐藏 loadingLayer，防止一直卡住
                            if (loadingLayer != null) loadingLayer.setVisibility(View.GONE);
                        });
                    }
                }).start();
            }
            @Override public void onStatusChanged(String provider, int status, Bundle extras) {}
            @Override public void onProviderEnabled(@NonNull String provider) {}
            @Override public void onProviderDisabled(@NonNull String provider) {}
        }, null);
    }
}